package com.wangwei.authoritySystem.config.security;

import com.wangwei.authoritySystem.common.utils.JwtUtils;
import com.wangwei.authoritySystem.config.redis.RedisService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Data
@Component
public class CheckTokenFilter extends OncePerRequestFilter {
    private String loginUrl = "/api/user/login";
    @Autowired
    private RedisService redisService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    CustomerUserDetailsService customerUserDetailsService;
    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            //获取当前请求的url地址
            String url = request.getRequestURI();
            //判断当前请求是否是登录请求，如果不是则需要验证token
            if (!url.equals(loginUrl)){
                //进行token认证
                this.validateToken(request);
            }
        } catch (AuthenticationException e) {
            loginFailureHandler.onAuthenticationFailure(request,response,e);
        }
        //登录请求不需要携带token，直接放行
        doFilter(request,response,filterChain);
    }

    /**
     * 验证token信息
     * @param request
     */
    private void validateToken(HttpServletRequest request){
        //获取前端提交过来的token
        //从headers获取
        String token = request.getHeader("token");
        //如果token为空，则从请求的参数获取
        if(ObjectUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        //如果headers和请求参数都没有token，则抛出异常
        if(ObjectUtils.isEmpty(token)){
            throw new CustomerAuthenticationException("token不存在");
        }
        //判断redis是否存在token
        String tokenKey = "token_"+ token;
        String redisToken = redisService.get(tokenKey);
        //判断redis中是否存在token,如果为空则表示token已经失效
        if(ObjectUtils.isEmpty(redisToken)){
            throw new CustomerAuthenticationException("token已过期");
        }
        //如果token和redis中的token不一致，则验证失败
        if(!token.equals(redisToken)){
            throw new CustomerAuthenticationException("token验证失败");
        }
        //如果token存在，则从token中解析出用户名
        String username = jwtUtils.getUsernameFromToken(token);
        //用户名为空
        if(ObjectUtils.isEmpty(username)){
            throw new CustomerAuthenticationException("token解析失败");
        }
        //获取用户信息
        UserDetails userDetails = customerUserDetailsService.loadUserByUsername(username);
        //判断用户信息是否为空
        if(userDetails == null){
            throw new CustomerAuthenticationException("token验证失败");
        }
        //创建用户身份认证对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        //设置请求信息
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        //将认证信息交给spring security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
